package com.tantinevincent.parser;

import com.tantinevincent.vector.DenseVector;
import com.tantinevincent.vector.LabeledVector;

/**
 * Parser raw data to vector by comma, no label will be save.
 * @author Vincent
 *
 */
public class CsvParser implements IParser{
	/**
	 * {@inheritDoc}
	 */
	@Override
	public LabeledVector parse(String s) {
		int commaCount = 0;
		for( char c : s.toCharArray() ){
			commaCount += (c==',')?1:0;
		}
		DenseVector dv = new DenseVector(commaCount+1);
		String[] tokens = s.split(",");
		int label = 0;
		try{
			label = Integer.parseInt(tokens[0]); //split out first toekn
		}catch(Exception ex){
			throwLibsvmFormatErrorException();
		}
		for( int i=1; i<=tokens.length-1; i++ ){
			double value = Double.parseDouble(tokens[i]);
			dv.set(i, value);
		}
		LabeledVector lv = new LabeledVector(dv,label);
		return lv;
	}
	/**
	 * Throw the data is not CSV format. That's it.
	 */
	private void throwLibsvmFormatErrorException(){
		try{
			new Exception("CSV format error. Please check the file.");
		}catch( Exception ex ){
			ex.printStackTrace();
			System.exit(-1);
		}
	}
	@Override
	public String toString(){
		return "CSV Parser, first colmun is label";
	}
}
